import React, { useState, useEffect, useRef } from 'react';
import { Modal, Input, Button, message } from 'antd';
import './index.css';

interface CaptchaProps {
  visible: boolean;
  onClose: () => void;
  onSuccess: (captchaCode: string) => void;
}

const Captcha: React.FC<CaptchaProps> = ({ visible, onClose, onSuccess }) => {
  const [captchaCode, setCaptchaCode] = useState('');
  const [captchaImage, setCaptchaImage] = useState('');
  const [loading, setLoading] = useState(false);
  const canvasRef = useRef<HTMLCanvasElement>(null);

  // 生成随机验证码
  const generateCaptcha = () => {
    const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    let result = '';
    for (let i = 0; i < 4; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
  };

  // 绘制验证码
  const drawCaptcha = (code: string) => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 设置背景
    ctx.fillStyle = '#f0f2f5';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 绘制干扰线
    for (let i = 0; i < 5; i++) {
      ctx.strokeStyle = `rgb(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)})`;
      ctx.beginPath();
      ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
      ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
      ctx.stroke();
    }

    // 绘制验证码文字
    ctx.font = '24px Arial';
    ctx.textBaseline = 'middle';
    
    for (let i = 0; i < code.length; i++) {
      ctx.fillStyle = `rgb(${Math.floor(Math.random() * 100)}, ${Math.floor(Math.random() * 100)}, ${Math.floor(Math.random() * 100)})`;
      const x = 20 + i * 25;
      const y = canvas.height / 2;
      const angle = (Math.random() - 0.5) * 0.5;
      
      ctx.save();
      ctx.translate(x, y);
      ctx.rotate(angle);
      ctx.fillText(code[i], 0, 0);
      ctx.restore();
    }

    // 绘制干扰点
    for (let i = 0; i < 50; i++) {
      ctx.fillStyle = `rgb(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)})`;
      ctx.fillRect(Math.random() * canvas.width, Math.random() * canvas.height, 1, 1);
    }
  };

  // 刷新验证码
  const refreshCaptcha = () => {
    const newCode = generateCaptcha();
    setCaptchaImage(newCode);
    drawCaptcha(newCode);
  };

  // 验证验证码
  const verifyCaptcha = () => {
    if (!captchaCode.trim()) {
      message.error('请输入验证码');
      return;
    }

    if (captchaCode.toLowerCase() !== captchaImage.toLowerCase()) {
      message.error('验证码错误，请重新输入');
      setCaptchaCode('');
      refreshCaptcha();
      return;
    }

    setLoading(true);
    // 模拟验证过程
    setTimeout(() => {
      setLoading(false);
      onSuccess(captchaCode);
      setCaptchaCode('');
      onClose();
    }, 1000);
  };

  // 处理键盘事件
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      verifyCaptcha();
    }
  };

  useEffect(() => {
    if (visible) {
      refreshCaptcha();
    }
  }, [visible]);

  return (
    <Modal
      title="安全验证"
      open={visible}
      onCancel={onClose}
      footer={null}
      width={400}
      centered
      maskClosable={false}
    >
      <div className="captcha-container">
        <div className="captcha-content">
          <p className="captcha-tip">请输入下方验证码完成安全验证</p>
          
          <div className="captcha-image-container">
            <canvas
              ref={canvasRef}
              width={120}
              height={40}
              className="captcha-canvas"
              onClick={refreshCaptcha}
            />
            <Button 
              type="link" 
              onClick={refreshCaptcha}
              className="refresh-btn"
            >
              刷新
            </Button>
          </div>

          <Input
            placeholder="请输入验证码"
            value={captchaCode}
            onChange={(e) => setCaptchaCode(e.target.value)}
            onKeyPress={handleKeyPress}
            maxLength={4}
            className="captcha-input"
            autoFocus
          />

          <div className="captcha-actions">
            <Button onClick={onClose} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button 
              type="primary" 
              onClick={verifyCaptcha}
              loading={loading}
            >
              确认
            </Button>
          </div>
        </div>
      </div>
    </Modal>
  );
};

export default Captcha;